﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Media.Animation;
using System.Windows.Interop;
using System.Text;
using ChrizNet.Log;
using ChrizNet.Localization;

namespace ChrizNet.MainApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Default Constructor.
        /// </summary>
        public App()
        {
            //Create new handle to avoid memory leakage issue in WPF
            //Reference: http://blogs.msdn.com/b/jgoldb/archive/2008/02/04/finding-memory-leaks-in-wpf-based-applications.aspx
            new HwndSource(new HwndSourceParameters());
        }

        /// <summary>
        /// Override the start up to enable the bootstrapper to load the main window.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //Default is 60 frames per seconds, try to minimize the animation frame rate to save CPU usage.. 
            Timeline.DesiredFrameRateProperty.OverrideMetadata(typeof(Timeline),
                new FrameworkPropertyMetadata { DefaultValue = 40 } //40 is still smooth
            );

            ChrizNetBootStrapper bootStrapper = new ChrizNetBootStrapper();
            bootStrapper.Run();
        }

        /// <summary>
        /// To capture unhandled exception in the application.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            Logger.Log(e.Exception);
            StringBuilder builder = new StringBuilder();
            builder.AppendLine(String.Format(LocalizationManager.GetLocalizedString("UnhandledExceptionError"), e.Exception.GetType().ToString(),
                e.Exception.StackTrace, e.Exception.Message));

            if (e.Exception.InnerException != null)
            {
                Logger.Log(e.Exception.InnerException);
                builder.AppendLine(e.Exception.InnerException.StackTrace);
            }

            //MessageBoxCustom messageDlg = new MessageBoxCustom(builder.ToString(), LocalizationManager.Title,
            //   MessageBoxCustomButton.OK, MessageBoxCustomIcon.Error);
            //messageDlg.Dialog.Owner = Application.Current.MainWindow;
            //messageDlg.ShowDialog();
        }
    }
}
